package com.eystar.ext.render.csv;

import java.io.File;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import com.jfinal.kit.Kv;
import com.jfinal.kit.PathKit;
import com.jfinal.render.Render;
import com.jfinal.render.RenderException;
import com.jfinal.template.Engine;
import com.jfinal.template.Template;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;

public class CSVRender extends Render{
    private List<?> datas;
    private String encodeType = "gbk";
    private String fileName = "default.csv";
    private String tplName;

    public CSVRender(String tplName, List<?> data) {
        this.tplName = tplName;
        this.datas = data;
        this.fileName = FileUtil.mainName(tplName) + "_" + DateUtil.format(new Date(), "yyyy_MM_dd_HH_mm_ss") + ".csv";
    }
    
    public CSVRender(String tplName, List<?> data,String fileName) {
        this.tplName = tplName;
        this.datas = data;
        this.fileName = fileName;
    }

    @Override
    public void render() {
        response.reset();
        PrintWriter out = null;
        try {
            response.setContentType("text/csv;charset=" + encodeType);
            response.setHeader("Content-Disposition",
            		"attachment;filename=" + URLEncoder.encode(fileName, encodeType));
            Engine engine = Engine.use();
        	// 读取模板
            Template template = engine.getTemplate(PathKit.getWebRootPath() + "/export/tpl/" + tplName);
        	// 待写入文件
            File file = new File(PathKit.getWebRootPath() + "/export/history/" + DateUtil.formatDate(new Date()) + "/" + fileName);
        	FileUtil.touch(file);
        	// 开始写入文件
        	template.render(Kv.by("datas", datas), file);
        	// 写入完成后，输出
        	FileUtil.writeToStream(file, response.getOutputStream());
        } catch (Exception e) {
            throw new RenderException(e);
        } finally {
            if (null != out) {
                out.flush();
                out.close();
            }
        }
    }

}
